package org.jetlinks.pro.datasource.rdb;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
import org.hswebframework.web.crud.configuration.EasyormProperties;
import org.hswebframework.web.validator.ValidatorUtils;

import javax.validation.constraints.NotBlank;
import java.util.Map;

@Getter
@Setter
public class RDBDataSourceProperties {

    private Type type;

    @Schema(description = "url")
    @NotBlank
    private String url;

    @NotBlank
    @Schema(description = "数据库")
    private String schema;

    @Schema(description = "用户名")
    private String username;

    @Schema(description = "密码")
    private String password;

    private Map<String, Object> others;

    private EasyormProperties.DialectEnum dialect;

    public EasyormProperties.DialectEnum getDialect() {
        if (null == dialect) {
            if (getUrl().contains("mysql")) {
                return EasyormProperties.DialectEnum.mysql;
            } else if (getUrl().contains("postgresql")) {
                return EasyormProperties.DialectEnum.postgres;
            } else if (getUrl().contains("oracle")) {
                return EasyormProperties.DialectEnum.oracle;
            } else if (getUrl().contains("mssql") || getUrl().contains("sqlserver")) {
                return EasyormProperties.DialectEnum.mssql;
            } else if (getUrl().contains("h2")) {
                return EasyormProperties.DialectEnum.h2;
            } else {
                throw new UnsupportedOperationException("unsupported database type");
            }
        }
        return dialect;
    }

    public RDBDataSourceProperties validate() {
        ValidatorUtils.tryValidate(this);
        return this;
    }

    public Type getType() {
        if (type == null) {
            type = url.startsWith("r2dbc") ? Type.r2dbc : Type.jdbc;
        }
        return type;
    }


    public enum Type {
        jdbc,
        r2dbc;
    }

}
